<?php
/**
 * 个人资料控制器
 */
namespace Admin\Controller;
use Think\Controller;

class ProfileController extends PublicController {

    //保存修改信息
    public function save(){
        if(!IS_AJAX){
            $this->ajaxReturn(['code' => 201, 'msg' => '非法请求方式']);
        }
        $admin_id = \admin_helper::get_admin_id();

        $admin_name  = I('admin_name', '', 'trim');

        $nick_name  = I('nick_name', '', 'trim');

        $password  = I('password', '', 'trim');

        //判断用户名是否为空，是否已存在
        if(!$admin_name){
            $this->ajaxReturn(['code' => 202, 'msg' => '登录账号不能为空']);
        }elseif(_uri('admin',array('admin_name' => $admin_name, 'id' => array('neq',$admin_id)))){
            $data = array(
                'code'=> 405,
                'msg' => '该登录账号已存在'
            );
            $this->ajaxReturn($data);
        }else{
            $data['admin_name'] = $admin_name;
        }
        //判断昵称是否为空，是否已存在
        if(!$nick_name){
            $data = array(
                'code'=> 410,
                'msg' => '用户昵称不能为空'
            );
            $this->ajaxReturn($data);
        }elseif(_uri('admin',array('nick_name' => $nick_name, 'id' => array('neq',$admin_id)))){
            $data = array(
                'code'=> 415,
                'msg' => '该用户昵称已存在'
            );
            $this->ajaxReturn($data);
        }else{
            $data['nick_name'] = $nick_name;
        }

        if($password){
            $data['password'] = password_encrypt($password);
        }

        $data['id'] = $admin_id;

        $result = M('admin')->save($data);

        if(false !== $result || 0 !== $result){
            //如果密码修改过，清除session，重新登录
            if($password){
                session('admin_id',null);
                $this->ajaxReturn(array('code' => 200, 'msg' => '个人资料修改成功，请重新登录'));
            }else{
                $this->ajaxReturn(array('code' => 200, 'msg' => '个人资料修改成功'));
            }

        }else{
            $this->ajaxReturn(array('code' => 400, 'msg' => '个人资料修改失败'));
        }



    }

    /*
     * 登录历史
     */
    public function history()
    {
        $model = 'login_history';

        //查询条件
        $filter = array();

        //获取总数据数
        $total = M($model)->where($filter)->count();
        if($total){
            //每页显示条数
            $per_num = 10;

            //调用分页函数
            $page = P($total, $per_num);
            //获取数据列表
            $list = M($model)->where($filter)->limit($page->limit())->order('`id` DESC')->select();
        }

        //将数据赋值到模板中
        $this->assign('search', $search);
        $this->assign('page', $page);
        $this->assign('list', $list);

        $this->display('history');

    }

}